import React from 'react'
import { error, info, Link, Toast, Input, Checkbox } from '../ui-components'
import { Button } from 'sq-ui';
import { connect } from 'react-redux'
import cookie from 'component-cookie'
import store from 'yields-store'
import rule from '../libs/rule'
import validate from '../libs/validate'
import style from './style'
import util from '../util'

@connect((auth) => ({auth}))
class Login extends React.Component {

	lock=false

	state= {
		rememberMe: 1,
    password: '',
    email: ''
	}

	handleRememberMe() {
		this.setState({
			rememberMe: this.state.rememberMe === 1? 0: 1
		})
	}

	handleInput(name) {
		return e => {
			this.setState({
				[name]: e.target.value
			})
		}
	}

  validate() {
    return this.props.validate(['email'], this)
  }

  handleBlur(name) {
    if (!this.state[name].trim()) return
    this.props.validate([name], this)
  }

	handleLogin() {
		if (this.lock) return
    // 校验规则
    if (this.validate()) return
    this.lock = true
    info('登录中..', true)
    this.props.login(this.state, res => {
      if (!/^20\d+$/.exec(res.code)) {
        this.lock = false
        error(res.msg)
      } else {
        const { data={} } = res
        const { onboardingUrl } = data
        if (onboardingUrl) {
          location.href = onboardingUrl;
          return
        }
        const { accessToken } = data
        if (!accessToken) return error('服务异常，请稍后重试..')
        const map = {
          'accessToken': 'X-Access-Token',
          'refreshToken': 'X-Refresh-Token'
        }
        for(let i in data) {
          //store(i, data[i])
          cookie(map[i], data[i], { path: '/', maxage: 1000*60*60*24*30 })
        }
        const {
          query = {}
        } = this.props.location;
        const {
          urlCode
        } = query;
        location.href = urlCode ? decodeURIComponent(urlCode) : '/';
      }
    })
	}

  componentDidMount() {
    const msg = util.getMessage()
    if (msg) {
      info(msg)
    }

    //this.props.tip(this.refs.email, 'hello world~~')
  }

	render() {
		return (
      <div>
        <div className={style.form}>
          <h2 className={style.title}>登录</h2>
          <div className={style.input}>
            <input 
              name={'email'}
              ref="email"
              autoFocus
              value={this.state.email}
              onChange={::this.handleInput('email')}
              onBlur={e => this.handleBlur('email')}
              autoComplete="off" 
              type="text" 
              placeholder="企业邮箱登录"
            />
          </div>
          <div className={style.input}>
            <input 
              name={'password'}
              ref="password"
              value={this.state.password}
              onChange={::this.handleInput('password')}
              autoComplete="off" 
              type="password" 
              onKeyPress={e => { if (e.which == 13) { this.handleLogin() } }}
              placeholder="密码"
            />
          </div>
          <div className={style['handle-password']}>
            <Checkbox 
              onClick={::this.handleRememberMe}
              active={this.state.rememberMe}
              label="记住密码" 
              className={style.checkbox}
            />
            <Link to='#/findpassword' label="忘记密码" _/>
          </div>
          <Button blue className={style.button} onClick={::this.handleLogin} label="登录" />
          <Link className={style.activate} label="首次登录，激活帐号" _ to="#/activate"/>
        </div>
      </div>
		)
	}
}

export default Login
